<template>
  <div class="template-designer">
    <!-- 顶部工具栏 -->
    <div class="designer-toolbar">
      <el-button-group>
        <el-button @click="addComponent('text')" icon="el-icon-edit">文本</el-button>
        <el-button @click="addComponent('table')" icon="el-icon-s-grid">表格</el-button>
        <el-button @click="addComponent('parameter')" icon="el-icon-data-line">参数</el-button>
        <el-button @click="addComponent('image')" icon="el-icon-picture">图片</el-button>
      </el-button-group>
      
      <div class="toolbar-actions">
        <el-button @click="previewTemplate" icon="el-icon-view">预览</el-button>
        <el-button @click="saveTemplate" type="primary" icon="el-icon-save">保存模板1</el-button>
        <el-button @click="generateReport" icon="el-icon-document">生成报告</el-button>
      </div>
    </div>

    <div class="designer-container">
      <!-- 左侧组件库 -->
      <div class="component-library">
        <h3>组件库</h3>
        <div
            v-for="element in componentList"
            :key="element.type"
            class="library-item"
            draggable="true"
            @dragstart="onNativeDragStart($event, element.type)"
          >
            <i :class="element.icon"></i>
            <span>{{ element.name }}</span>
          </div>
      </div>

      <!-- 中间设计画布 -->
      <div class="design-canvas">
        <div class="canvas-header">
          <h3>{{ currentTemplate.name || '未命名模板' }}</h3>
          <el-select v-model="currentTemplate.pageSize" size="mini" style="width: 120px">
            <el-option label="A4" value="A4"></el-option>
            <el-option label="A3" value="A3"></el-option>
            <el-option label="自定义" value="custom"></el-option>
          </el-select>
        </div>

        <!-- 关键修复：事件绑定移到 canvas-content -->
        <div 
          class="canvas-content" 
          :style="canvasStyle" 
          :class="{ 'drag-over': isDragOver }"
          @drop="handleDrop"
          @dragover="handleDragOver"
          @dragenter="handleDragEnter"
          @dragleave="handleDragLeave"
        >
        <template-renderer
        :components="currentTemplate.components"
        :config="config"
        :mode="'design'"
        :selected-component-id="selectedComponent?.id"
        :dragging-component-id="draggingComponentId"
        :grid-config="gridConfig"
        @select-component="handleSelectComponent"
        @update-component="handleUpdateComponent"
        @component-remove="handleComponentRemove"
        @drag-start="handleComponentDragStart"
        @drag-end="handleComponentDragEnd"
        @component-move="handleComponentMove"
        @component-resize="handleComponentResize"
      />
        </div>
      </div>

      <!-- 右侧属性面板 -->
      <div class="property-panel">
        <h3>属性设置</h3>
        <div v-if="selectedComponent">
          <component-property-editor
            :component="selectedComponent"
            :config="config"
            @update="handlePropertyUpdate"
            @delete="handleComponentDelete"
            @duplicate="handleComponentDuplicate"
          />
        </div>
        <div v-else class="no-selection">
          <i class="el-icon-info"></i>
          <p>请选择要编辑的组件</p>
        </div>

        <!-- 栅格配置 -->
  <div class="property-section">
    <h4 class="section-title">栅格配置</h4>
    <el-form :model="gridConfig" label-width="80px" size="mini">
      <el-form-item label="显示栅格">
        <el-switch v-model="gridConfig.enabled" />
      </el-form-item>
      <el-form-item label="启用吸附">
        <el-switch v-model="gridConfig.snap" />
      </el-form-item>
      <el-form-item label="栅格大小">
        <el-input-number
          v-model="gridConfig.size"
          :min="5"
          :max="50"
          :step="5"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item label="吸附容差">
        <el-input-number
          v-model="gridConfig.snapTolerance"
          :min="1"
          :max="10"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item label="栅格颜色">
        <el-color-picker v-model="gridConfig.color" />
      </el-form-item>
    </el-form>
  </div>
      </div>
    </div>

    <!-- 预览对话框 -->
    <template-preview-dialog
      :visible="previewVisible"
      :template="currentTemplate"
      :test-data="testData"
      @close="previewVisible = false"
      @generate="handleGenerate"
    />
  </div>
</template>

<script>
// import vueDraggable from 'vuedraggable'
import TemplateRenderer from './TemplateRenderer.vue'
import ComponentPropertyEditor from './ComponentPropertyEditor.vue'
import TemplatePreviewDialog from './TemplatePreviewDialog.vue'
import { generateId, deepClone } from '@/utils/tools'

export default {
  name: 'TemplateDesigner',
  components: {
    // vueDraggable,
    TemplateRenderer,
    ComponentPropertyEditor,
    TemplatePreviewDialog
  },
  props: {
    config: {
      type: Object,
      required: true
    },
    initialTemplate: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      currentTemplate: {
        id: '',
        name: '新建模板',
        type: 'record', // record: 原始记录, report: 报告
        pageSize: 'A4',
        components: []
      },
      componentList: [
        { type: 'text', name: '文本', icon: 'el-icon-edit' },
        { type: 'number', name: '数值', icon: 'el-icon-data-analysis' },
        { type: 'parameter', name: '参数', icon: 'el-icon-data-line' },
        { type: 'multiMeasure', name: '多测次', icon: 'el-icon-collection' },
        { type: 'dynamicTable', name: '动态表格', icon: 'el-icon-s-grid' },
        { type: 'image', name: '图片', icon: 'el-icon-picture' },
        { type: 'header', name: '页眉', icon: 'el-icon-document' },
        { type: 'footer', name: '页脚', icon: 'el-icon-document' },
        { type: 'signature', name: '签名', icon: 'el-icon-edit' },
        { type: 'layoutTable', name: '表格', icon: 'el-icon-s-grid' }
      ],
      selectedComponent: null,
      previewVisible: false,
      testData: {},
      isDragOver: false,
      draggingComponentId: null,
      gridConfig: {
      enabled: true,      // 是否显示栅格
      size: 20,          // 栅格大小（像素）
      snap: true,        // 是否启用吸附
      snapTolerance: 5,  // 吸附容差（像素）
      color: '#e0e0e0',  // 栅格颜色
      showGuides: true   // 显示对齐参考线
    },
    // 对齐参考线状态
    alignmentGuides: {
      vertical: [],
      horizontal: [],
      visible: false
    }
    }
  },
  computed: {
    canvasStyle() {
      const styles = {}
      if (this.currentTemplate.pageSize === 'A4') {
        styles.width = '210mm'
        styles.minHeight = '297mm'
      } else if (this.currentTemplate.pageSize === 'A3') {
        styles.width = '297mm'
        styles.minHeight = '420mm'
      }
      return styles
    }
  },
  created() {
    this.initializeTemplate()
  },
  methods: {
      onNativeDragStart(evt, type) {
    evt.dataTransfer.setData('text/plain', type)
    evt.dataTransfer.effectAllowed = 'copy'
  },
    // 拖拽开始：传递组件类型
    onDragStart(evt) {
      console.log('拖拽开始，组件类型：', evt.item.dataset.type)
      const componentType = evt.item.dataset.type
      const nativeEvent = evt.originalEvent || evt
      const dataTransfer = nativeEvent.dataTransfer

      if (dataTransfer && componentType) {
        dataTransfer.setData('text/plain', componentType)
        dataTransfer.effectAllowed = 'copy'
        dataTransfer.setDragImage(evt.item, 0, 0) // 设置拖拽预览图
      }
    },

    initializeTemplate() {
      if (this.initialTemplate) {
        this.currentTemplate = deepClone(this.initialTemplate)
      } else {
        this.currentTemplate.id = `TEMPLATE_${generateId(8)}`
      }
    },

    // 拖拽经过：阻止默认行为
    handleDragOver(e) {
      e.preventDefault()
      e.stopPropagation()
      e.dataTransfer.dropEffect = 'copy'
    },

    // 拖拽进入：高亮画布
    handleDragEnter(e) {
      e.preventDefault()
      e.stopPropagation()
      this.isDragOver = true
    },

    // 拖拽离开：取消高亮（仅当离开画布内容区时）
    handleDragLeave(e) {
      e.preventDefault()
      e.stopPropagation()
      const canvasContent = this.$el.querySelector('.canvas-content')
      if (canvasContent && !canvasContent.contains(e.relatedTarget)) {
        this.isDragOver = false
      }
    },

    // 拖拽释放：添加组件到画布
    handleDrop(e) {
      e.preventDefault()
      e.stopPropagation()
      this.isDragOver = false

      const componentType = e.dataTransfer.getData('text/plain')
      console.log('触发drop事件，获取到的组件类型：', componentType)

      if (componentType) {
        // 计算相对于画布内容区的准确坐标（减去内边距）
        const canvasContent = this.$el.querySelector('.canvas-content')
        const rect = canvasContent.getBoundingClientRect()
        const paddingLeft = parseInt(window.getComputedStyle(canvasContent).paddingLeft)
        const paddingTop = parseInt(window.getComputedStyle(canvasContent).paddingTop)
        
        const x = e.clientX - rect.left - paddingLeft
        const y = e.clientY - rect.top - paddingTop
        const finalX = Math.max(0, x)
        const finalY = Math.max(0, y)

        this.addComponent(componentType, finalX, finalY)
      } else {
        this.$message.warning('未识别的组件类型，无法添加')
      }
    },

    // 添加组件（响应式更新）
    addComponent(type, x = 50, y = 50) {
      const baseComponent = {
        id: `COMP_${generateId(8)}`,
        type,
        position: { x, y, width: 180, height: 40 },
        style: {},
        content: {},
        zIndex: this.currentTemplate.components.length + 1
      }

      switch (type) {
        case 'text':
          Object.assign(baseComponent, {
            content: {
              text: '请输入文本内容',
              fontSize: 14,
              fontWeight: 'normal',
              align: 'left',
              color: '#000000'
            }
          })
          break
        // case 'table':
        //   Object.assign(baseComponent, {
        //     position: { ...baseComponent.position, width: 350, height: 180 },
        //     content: {
        //       headers: ['参数', '数值', '单位'],
        //       data: [],
        //       showHeader: true,
        //       border: true
        //     }
        //   })
        //   break
        case 'layoutTable':
      Object.assign(baseComponent, {
        position: { ...baseComponent.position, width: 500, height: 250 },
        content: {
          rows: [
            {
              height: 100,
              cells: [
                { width: 150, height: 100, components: [] },
                { width: 150, height: 100, components: [] },
                { width: 150, height: 100, components: [] }
              ]
            },
            {
              height: 100,
              cells: [
                { width: 150, height: 100, components: [] },
                { width: 150, height: 100, components: [] },
                { width: 150, height: 100, components: [] }
              ]
            }
          ],
          merges: []
        }
      })
      break
        case 'parameter':
          Object.assign(baseComponent, {
            content: {
              paramCode: '',
              displayName: '',
              format: 'value', // value, valueWithUnit, nameValue
              precision: 2
            }
          })
          break
        case 'image':
          Object.assign(baseComponent, {
            position: { ...baseComponent.position, width: 200, height: 150 },
            content: {
              imageUrl: '',
              alt: '',
              width: '100%',
              height: 'auto',
              align: 'center'
            }
          })
          break
        case 'header':
          Object.assign(baseComponent, {
            position: { ...baseComponent.position, width: '100%', height: 80 },
            content: {
              title: '检测报告',
              subtitle: '',
              logo: null,
              showBorder: true
            }
          })
          break
        case 'footer':
          Object.assign(baseComponent, {
            position: { ...baseComponent.position, width: '100%', height: 60 },
            content: {
              leftText: '',
              centerText: '',
              rightText: '',
              signatureLines: [],
              footerInfo: '',
              showBorder: true
            }
          })
          break
        case 'signature':
          Object.assign(baseComponent, {
            content: {
              signer: '',
              title: '',
              date: ''
            }
          })
          break
        case 'number':
      Object.assign(baseComponent, {
        content: {
          paramCode: '',
          displayName: '',
          showUnit: true,
          precision: 2,
          align: 'left',
          fontSize: 14
        }
      })
      break
      
    case 'multiMeasure':
      Object.assign(baseComponent, {
        position: { ...baseComponent.position, width: 250, height: 120 },
        content: {
          paramCode: '',
          displayName: '',
          showStatistics: true,
          precision: 2
        }
      })
      break
      
    case 'dynamicTable':
      Object.assign(baseComponent, {
        position: { ...baseComponent.position, width: 400, height: 200 },
        content: {
          groupId: '',
          showHeader: true,
          border: true
        }
      })
      break
      }

      // 响应式添加组件，确保TemplateRenderer实时渲染
      this.$set(this.currentTemplate.components, this.currentTemplate.components.length, baseComponent)
      this.selectedComponent = baseComponent
      this.$message.success(`已添加${this.getComponentName(type)}组件`)
      console.log('组件添加成功，当前组件列表：', this.currentTemplate.components)
    },

    getComponentName(type) {
      const component = this.componentList.find(item => item.type === type)
      return component ? component.name : type
    },

    handleSelectComponent(component) {
      this.selectedComponent = component
    },

    handleUpdateComponent(componentId, updates) {
      const index = this.currentTemplate.components.findIndex(comp => comp.id === componentId)
      if (index !== -1) {
        this.$set(this.currentTemplate.components, index, {
          ...this.currentTemplate.components[index],
          ...updates
        })
      }
    },

    handlePropertyUpdate(updates) {
      if (this.selectedComponent) {
        const index = this.currentTemplate.components.findIndex(
          comp => comp.id === this.selectedComponent.id
        )
        if (index !== -1) {
          this.$set(this.currentTemplate.components, index, {
            ...this.currentTemplate.components[index],
            ...updates
          })
          this.selectedComponent = this.currentTemplate.components[index]
        }
      }
    },

    handleComponentDelete(componentId) {
      const index = this.currentTemplate.components.findIndex(comp => comp.id === componentId)
      if (index !== -1) {
        this.currentTemplate.components.splice(index, 1)
        this.selectedComponent = null
        this.$message.success('组件已删除')
      }
    },

    handleComponentDuplicate(component) {
      const duplicated = deepClone(component)
      duplicated.id = `COMP_${generateId(8)}`
      duplicated.position.x += 20
      duplicated.position.y += 20
      this.$set(this.currentTemplate.components, this.currentTemplate.components.length, duplicated)
      this.selectedComponent = duplicated
      this.$message.success('组件已复制')
    },

    handleComponentRemove(componentId) {
      this.handleComponentDelete(componentId)
    },

    handleComponentDragStart(component) {
      this.draggingComponentId = component.id
    },

    handleComponentDragEnd() {
      this.draggingComponentId = null
    },

    handleComponentMove({ componentId, x, y }) {
      const component = this.currentTemplate.components.find(comp => comp.id === componentId)
      if (component) {
        this.$set(component.position, 'x', x)
        this.$set(component.position, 'y', y)
      }
    },

    handleComponentResize({ componentId, width, height }) {
      const component = this.currentTemplate.components.find(comp => comp.id === componentId)
      if (component) {
        this.$set(component.position, 'width', width)
        this.$set(component.position, 'height', height)
      }
    },

    previewTemplate() {
      this.loadTestData()
      this.previewVisible = true
    },

    async loadTestData() {
      try {
        const savedData = localStorage.getItem('detectionConfig')
        if (savedData) {
          this.testData = JSON.parse(savedData)
        }
      } catch (error) {
        console.error('加载测试数据失败:', error)
      }
    },

    async saveTemplate() {
      try {
         console.log('模板数据:', this.currentTemplate)
        // await this.$api.template.save(this.currentTemplate)
        this.$message.success('模板保存成功')
      } catch (error) {
        console.error('保存模板失败:', error)
        this.$message.error('保存模板失败')
      }
    },

    async generateReport() {
      try {
        // const result = await this.$api.report.generate({
        //   templateId: this.currentTemplate.id,
        //   data: this.testData
        // })
        // this.downloadFile(result)
        this.$message.success('报告生成成功')
      } catch (error) {
        console.error('生成报告失败:', error)
        this.$message.error('生成报告失败')
      }
    },

    downloadFile(fileData) {
      const blob = new Blob([fileData.content], { type: fileData.contentType })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = fileData.filename
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    },

    handleGenerate(format) {
      this.generateReport(format)
      this.previewVisible = false
    }
  }
}
</script>

<style scoped>
.template-designer {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

.designer-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background: white;
  border-bottom: 1px solid #e6e8eb;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.designer-container {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.component-library {
  width: 200px;
  background: white;
  border-right: 1px solid #e6e8eb;
  padding: 15px;
  overflow-y: auto;
}

.component-library h3 {
  margin: 0 0 15px 0;
  font-size: 14px;
  color: #303133;
}

.library-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  margin-bottom: 8px;
  background: #f8f9fa;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  cursor: move;
  transition: all 0.3s;
  user-select: none;
}

.library-item:hover {
  border-color: #409eff;
  background: #f0f9ff;
  transform: translateY(-2px);
}

.library-item i {
  margin-right: 8px;
  color: #409eff;
}

.design-canvas {
  flex: 1;
  background: #f0f2f5;
  padding: 20px;
  overflow: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.canvas-header {
  width: 100%;
  max-width: 800px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 20px;
}

.canvas-content {
  background: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  padding: 10mm;
  position: relative;
  transition: all 0.3s;
  min-height: 400px;
}

.canvas-content.drag-over {
  background: #f0f9ff;
  border: 2px dashed #409eff;
  box-shadow: 0 0 20px rgba(64, 158, 255, 0.2);
}

.empty-canvas-hint {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: #c0c4cc;
  z-index: 1;
}

.empty-canvas-hint i {
  font-size: 48px;
  margin-bottom: 16px;
  display: block;
}

.empty-canvas-hint p {
  margin: 0;
  font-size: 14px;
}

.property-panel {
  width: 300px;
  background: white;
  border-left: 1px solid #e6e8eb;
  padding: 15px;
  overflow-y: auto;
}

.property-panel h3 {
  margin: 0 0 15px 0;
  font-size: 14px;
  color: #303133;
}

.no-selection {
  text-align: center;
  color: #909399;
  padding: 40px 20px;
}

.no-selection i {
  font-size: 48px;
  margin-bottom: 16px;
  color: #c0c4cc;
}
</style>